<script setup>
import { reactive, ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from 'vue-router'
import { removeToken } from "@/composables/cookie";
import { showMessage, showModel } from "@/composables/util.js";
import { updatePassword, updateUserInfo, findCollectPageList } from "@/api/common/user"
import { uploadFile } from "@/api/common/file"
import moment from 'moment'

// 从浏览器本地存储中取出用户信息
let userInfo = JSON.parse(localStorage.getItem("userInfo"))
const route = useRoute()
const router = useRouter()
// 控制个人信息弹出框
let info = ref(false)
let password = ref(false)
// 设置导航栏激活项
const activeIndex = ref('1')
const form1 = reactive({
  id: null,
  username: null,
  avatar: null,
  token: null
})
const form2 = reactive({
  username: '',
  password: '',
  newPassword: '',
  surePassword: ''
})
onMounted(() => {
    if(userInfo !== null) {
      form1.id = userInfo.id
      form1.username = userInfo.username
      form1.avatar = userInfo.avatar
      form1.token = userInfo.token
      form2.username = userInfo.username
    } 
})

// 修改用户信息
const saveInfo = () => {
    updateUserInfo(form1).then((res) => {
        if (res.data.success === true) {
            showMessage('修改成功')
            localStorage.setItem("userInfo", JSON.stringify(res.data.data))
            userInfo = JSON.parse(localStorage.getItem("userInfo"))
            info = false
            window.location.reload();
        } else {
            showMessage(res.data.message, 'error')
        }
    })
}

// 修改用户密码
const savePassword = () => {
    updatePassword(form2).then((res) => {
        if (res.data.success === true) {
            showMessage('修改成功')
            removeToken()
            localStorage.removeItem('userInfo')
            router.push('/login')
        } else {
            showMessage(res.data.message, 'error')
        }
    })
}

// 退出登录方法
const logout = () => {
    showModel('是否退出登录?').then(() => {
        removeToken()
        localStorage.removeItem('userInfo')
        showMessage('退出登录成功!')
        router.push('/login')
    })
}

function goIndex() {
    router.push('/')
}

function goLogin() {
    router.push('/login')
}

// 当前页码，初值默认为1
const current = ref(1)
// 总记录数，初值默认为0
const total = ref(0)
// 每页显示的记录数，初值默认为10
const size = ref(10)
const collectList = ref([])

// 获取分页数据
function getCollectPageList() {
    console.log('获取收藏列表，参数：', {
        userId: userInfo.id,
        current: current.value,
        size: size.value
    })
    findCollectPageList({ 
        userId: userInfo.id,
        current: current.value, 
        size: size.value
    }).then((res) => {
        if (res.data.success == true) {
            console.log('收藏列表数据：', res.data.data)
            collectList.value = res.data.data
            current.value = res.data.current
            size.value = res.data.size
            total.value = res.data.total
        }
    })
}

// 初始加载数据
getCollectPageList()

// 处理页码改变
const handleCurrentChange = (val) => {
    current.value = val
    getCollectPageList()
}

// 处理每页条数改变
const handleSizeChange = (val) => {
    size.value = val
    current.value = 1
    getCollectPageList()
}

// 查看课程详情
const viewCourse = (course) => {
    console.log('课程详情：', course) // 添加日志查看数据结构
    if (course.type === 0) {
        router.push(`/article/${course.id}`)
    } else {
        router.push(`/video/${course.id}`)
    }
}
</script>

<template>
    <!-- 主容器使用Element布局 -->
    <el-container class="home-container">
        <!-- 导航栏 -->
        <el-header class="header">
            <div class="nav-container">
                <div class="logo">
                    高校<span class="blue">互联网技术</span>在线学习平台
                </div>
                <el-menu mode="horizontal" :default-active="activeIndex">
                    <el-menu-item index="1">
                        <router-link to="/">首页</router-link>
                    </el-menu-item>
                    <el-menu-item index="2">
                        <router-link to="/article-course">图文课程</router-link>
                    </el-menu-item>
                    <el-menu-item index="3">
                        <router-link to="/video-course">视频课程</router-link>
                    </el-menu-item>
                </el-menu>
                <div class="search-box">
                    <el-input placeholder="搜索课程..." suffix-icon="Search" class="search-input" />
                </div>
                <!-- 未登录状态 -->
                <div class="user-wrapper" v-if="!userInfo">
                    <el-button type="primary" class="login-btn" @click="goLogin" round>
                        <i class="el-icon-user"></i>
                        <span>登录 / 注册</span>
                    </el-button>
                </div>

                <!-- 已登录状态 -->
                <div class="user-panel" v-else>
                    <el-dropdown trigger="hover">
                        <div class="user-card">
                            <div class="profile">
                                <el-avatar :src="userInfo.avatar" :size="36" class="user-avatar"
                                    :style="{ backgroundColor: '#8ac8ff' }" />
                            </div>
                        </div>

                        <!-- 下拉菜单 -->
                        <template #dropdown>
                            <el-dropdown-menu class="user-menu">
                                <el-dropdown-item class="menu-item" @click="info = true">
                                    <i class="el-icon-user-solid"></i>个人信息
                                </el-dropdown-item>
                                <el-dropdown-item class="menu-item" @click="router.push('/order')">
                                    <i class="el-icon-time"></i>我的订单
                                </el-dropdown-item>
                                <el-dropdown-item class="menu-item" @click="router.push('/collect')">
                                    <i class="el-icon-star-off"></i>我的收藏
                                </el-dropdown-item>
                                <el-dropdown-item class="menu-item" @click="password = true">
                                    <i class="el-icon-lock"></i>修改密码
                                </el-dropdown-item>
                                <el-dropdown-item class="menu-item logout" @click="logout">
                                    <i class="el-icon-switch-button"></i>退出登录
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </div>
        </el-header>

        <!-- 收藏列表主体 -->
        <el-main>
            <div class="collect-container">
                <el-card class="collect-card">
                    <template #header>
                        <div class="card-header">
                            <h2>我的收藏</h2>
                        </div>
                    </template>

                    <!-- 收藏列表 -->
                    <el-table :data="collectList" style="width: 100%" v-loading="loading">
                        <el-table-column label="课程封面" width="180">
                            <template #default="scope">
                                <el-image 
                                    style="width: 120px; height: 80px" 
                                    :src="scope.row.cover"
                                    fit="cover"
                                    @click="viewCourse(scope.row)"
                                    class="clickable-image"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column prop="title" label="课程名称">
                            <template #default="scope">
                                <div class="course-title clickable" @click="viewCourse(scope.row)">
                                    {{ scope.row.title }}
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="课程类型" width="120">
                            <template #default="scope">
                                <el-tag :type="scope.row.type === 0 ? 'success' : 'primary'">
                                    {{ scope.row.type === 0 ? '图文课程' : '视频课程' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="price" label="价格" width="120">
                            <template #default="scope">
                                <span class="price">¥{{ scope.row.price?.toFixed(2) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="createTime" label="收藏时间" width="180">
                            <template #default="scope">
                                {{ moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
                            </template>
                        </el-table-column>
                    </el-table>

                    <!-- 分页 -->
                    <div class="pagination-container">
                        <el-pagination
                            v-model:current-page="current"
                            v-model:page-size="size"
                            :page-sizes="[10, 20, 30, 50]"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                        />
                    </div>
                </el-card>
            </div>
        </el-main>
    </el-container>

    <!--个人信息对话框-->
    <el-dialog v-model="info" title="个人信息" width="500px" class="custom-dialog">
        <el-form :model="form1" label-width="80px" style="padding: 10px;">
            <el-form-item label="头像">
                <div style="display: flex; align-items: center;">
                    <el-avatar :src="form1.avatar" :icon="UserFilled"
                        style="background-color: #8ac8ff; margin-right: 10px;" />
                    <el-upload :on-change="handleAvatarChange" :auto-upload="false" :show-file-list="false"
                        :file-list="fileList">
                        <el-button size="small" type="primary">修改头像</el-button>
                    </el-upload>
                </div>
            </el-form-item>

            <el-form-item label="用户名">
                <el-input v-model="form1.username" autocomplete="off" placeholder="请输入用户名" style="width: 130px" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer" style="text-align: right;">
                <el-button @click="info = false">取消</el-button>
                <el-button type="primary" @click="saveInfo">保存</el-button>
            </div>
        </template>
    </el-dialog>

    <!--修改密码对话框-->
    <el-dialog v-model="password" title="修改密码" width="500px" class="custom-dialog">
        <el-form :model="form2" label-width="80px" style="padding: 10px;">
            <el-form-item label="旧密码">
                <el-input type="password" v-model="form2.password" autocomplete="off" placeholder="请输入旧密码"
                    style="width: 200px" />
            </el-form-item>
            <el-form-item label="新密码">
                <el-input type="password" v-model="form2.newPassword" autocomplete="off" placeholder="请输入新密码"
                    style="width: 200px" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer" style="text-align: right;">
                <el-button @click="password = false">取消</el-button>
                <el-button type="primary" @click="savePassword">保存</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>
$primary-blue: #409EFF;
$hover-blue: rgba(64, 158, 255, 0.1);

.collect-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.collect-card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        h2 {
            margin: 0;
            font-size: 20px;
            color: #303133;
        }
    }
}

.clickable-image {
    cursor: pointer;
    transition: transform 0.3s;

    &:hover {
        transform: scale(1.05);
    }
}

.course-title {
    color: #303133;
    cursor: pointer;

    &:hover {
        color: $primary-blue;
    }
}

.price {
    color: #f56c6c;
    font-weight: bold;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}

.home-container {
    background: #fff;
    min-height: 100vh;

    /* 容器布局 */
    .header {
        height: 70px !important;
        background: #ffffff;
        border-bottom: 1px solid #ebeef5;
    }

    .nav-container {
        max-width: 1440px;
        margin: 0 auto;
        display: flex;
        align-items: center;
        height: 100%;
        padding: 0 24px;
    }

    /* Logo样式 */
    .logo {
        font-size: 24px;
        font-weight: 600;
        margin-right: 48px;
        color: #303133;
    }

    .logo .blue {
        color: #409eff;
    }

    /* 导航菜单核心配置 */
    .el-menu--horizontal {
        background: transparent !important;
        border-bottom: none !important;
        flex: 1;
    }

    .el-menu-item {
        height: 64px;
        line-height: 64px;
        font-size: 16px;
        padding: 0 28px;
        color: #606266;
        transition: color 0.3s;
    }

    .el-menu-item.is-active {
        color: #409eff !important;
        border-bottom: 2px solid #409eff;
    }

    /* 搜索框定制 */
    .search-box {
        margin-left: auto;
        margin-right: 24px;
    }

    .search-box .el-input {
        --el-input-border-radius: 20px;
        --el-input-bg-color: #f5f7fa;
    }

    .search-box .el-input__wrapper {
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
    }

    /* 用户面板 */
    .user-panel .el-button {
        border-radius: 20px;
        padding: 10px 24px;
        background: #409eff;
        color: white;
    }
}
</style> 